python 将matplotlib绘制的图表赋给一个img对象 matplotlib输出图形到网页 您所在的位置:网站首页 python matplotlib 输出网页 python 将matplotlib绘制的图表赋给一个img对象 matplotlib输出图形到网页

python 将matplotlib绘制的图表赋给一个img对象 matplotlib输出图形到网页

2024-06-20 06:21| 来源: 网络整理| 查看: 265

Python最常用的绘图库,提供了一整套十分适合交互式绘图的命令 API,比较方便的就可以将其嵌入到GUI应用程序中。

官网:https://matplotlib.org/

学习方式:从官网examples入门学习:

https://matplotlib.org/examples/index.html

https://matplotlib.org/gallery.html

1.Matplotlib 是一个非常强大的 Python 画图工具.。

2.手中有很多数据, 可是不知道该怎么呈现这些数据.,Matplotlib它能帮你画出美丽的: 线图; 散点图; 等高线图; 条形图; 柱状图; 3D 图形, 甚至是图形动画等等

基本使用

设置在jupyter中matplotlib的显示情况:

1.%matplotlib tk 在GUI中显示。

2.%matplotlib inline 在行内显示。

figure

figure:图形,matplotlib中的所有图像都是位于figure对象中,一个图像只能 有一个figure对象。matplotlib 的 figure 就是一个 单独的 figure 小窗口, 小窗口 里面还可以有更多的小图片.。

import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import pandas as pd # 设置中文显示 mpl.rcParams['font.sans-serif'] = ['SimHei'] mpl.rcParams['axes.unicode_minus'] = False data = np.arange(-3,3,0.1) x = np.sin(data) y = np.cos(data) # 画图 ''' figsize:图形的大小 facecolor:边框的背景颜色 ''' # plt.figure(frameon=False,facecolor='green') # plt.plot(data,x,) # 第一个线图 # # plt.figure(figsize = (8,6)) # plt.plot(data,y) # 第二个线图 # # plt.figure(facecolor='red') # plt.plot(data,x,) # 第三个线图第一条线 # plt.plot(data,y) # 第三个线图第二条线 plt.figure(facecolor='red') plt.plot(data,x,data,y) # 不常见 plt.plot(x) # 如果只有一个参数这个参数 默认是Y轴的数据,X默认是从 0 - n # plt.axis('off') plt.show()颜色、标记和线型

plot(x,y,color='red', linestyle='dashed', marker='o'.....)。

绘图中用到的直线属性包括:

(1)LineStyle:线形。

(2)LineWidth:线宽。

(3)Color:颜色。

(4)Marker:标记点的形状。

(5)label:用于图例的标签。

import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import pandas as pd # 设置中文显示 mpl.rcParams['font.sans-serif'] = ['SimHei'] mpl.rcParams['axes.unicode_minus'] = False data = np.arange(-3,3,0.1) x = np.sin(data) y = np.cos(data) plt.figure() # plt.plot(x,y,color = 'y') # 设置颜色 # plt.plot(x,y,color = 'y',linestyle = '--') # plt.plot(x,y,color = 'y',linestyle = '--',linewidth = 5,marker = '*',markersize = 20) # plt.plot(x,y,color = 'y',linestyle = '--',marker = 'o',label = 'x-line') plt.plot(x,y,'*b--',label = 'x-line',markersize=20) # 简写方式 plt.legend(loc='lower right') plt.axis('off') plt.show()

线型:

''' '-' solid line style '--' dashed line style(线虚) '-.' dash-dot line style ':' dotted line style(点虚) '''

market:

https://matplotlib.org/api/markers_api.html

python 将matplotlib绘制的图表赋给一个img对象 matplotlib输出图形到网页_中文显示

python 将matplotlib绘制的图表赋给一个img对象 matplotlib输出图形到网页_html_02

''' '.' point marker ',' pixel marker 'o' circle marker 'v' triangle_down marker '^' triangle_up marker '' triangle_right marker '1' tri_down marker '2' tri_up marker '3' tri_left marker '4' tri_right marker 's' square marker 'p' pentagon marker '*' star marker 'h' hexagon1 marker 'H' hexagon2 marker '+' plus marker 'x' x marker 'D' diamond marker 'd' thin_diamond marker '|' vline marker '_' hline marker '''

View text

颜色:

https://matplotlib.org/users/colormaps.html

https://matplotlib.org/examples/color/colormaps_reference.html

由其文档可知,在 colormap 类别上,有如下分类:

perceptual uniform sequential colormaps:感知均匀的序列化 colormapsequential colormaps:序列化(连续化)色图 colormap;gray:0-255 级灰度,0:黑色,1:白色,黑底白字;gray_r:翻转 gray 的显示,如果 gray 将图像显示为黑底白字,gray_r 会将其显示为白底黑字;binarydiverging colormaps:两端发散的色图 colormaps;seismicqualitative colormaps:量化(离散化)色图;miscellaneous colormaps:其他色图;rainbow

python 将matplotlib绘制的图表赋给一个img对象 matplotlib输出图形到网页_中文显示

python 将matplotlib绘制的图表赋给一个img对象 matplotlib输出图形到网页_html_02

import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import pandas as pd # 设置中文显示 mpl.rcParams['font.sans-serif'] = ['SimHei'] mpl.rcParams['axes.unicode_minus'] = False dat = np.random.randint(0,255,(20,30)) dat2 = dat.reshape(-1) '''方法1''' # # 画图 # plt.scatter([i for i in range(600)],dat2,marker='.',c=dat2,cmap=plt.get_cmap('gray_r')) # # plt.scatter([i for i in range(600)],dat2,marker='.',c=dat2, cmap=plt.cm.binary) #与'gray_y'一个效果。 # # plt.imshow(dat, cmap=plt.cm.binary) # plt.colorbar() # # plt.figure() # plt.scatter([i for i in range(600)],dat2,c=dat2,marker='.', cmap='gray') # plt.colorbar() '''方法2''' plt.figure() from matplotlib.colors import ListedColormap data = np.random.randint(1,5,(30,)) colors = ('lightgreen', 'cyan', 'gray', 'r', 'b') # cmp = ListedColormap(colors[:len(np.unique(data))]) cmp = ListedColormap(colors) plt.scatter([i for i in range(30)],data,marker='.',c=data,cmap=cmp) plt.colorbar() # 展示图片 plt.show()

获取色标

python 将matplotlib绘制的图表赋给一个img对象 matplotlib输出图形到网页_中文显示

python 将matplotlib绘制的图表赋给一个img对象 matplotlib输出图形到网页_html_02

import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np ''' (a)根据颜色名称(name)或者(Hex)生成 方法为cmap = mpl.colors.ListedColormap(clist),clist是包含有颜色名称或16进制码的列表,比如 ''' cmap_list=[0]*3 cmap_list[0]=['r','g','b','c'] cmap_list[1]=['forestgreen','springgreen','yellowgreen','lightsteelblue','deepskyblue'] cmap_list[2]=['#FAEBD7','#00FFFF','#FF7F50','#006400'] gradient = np.linspace(0, 1, 256) gradient = np.vstack((gradient, gradient)) fig, axes = plt.subplots(nrows=3) fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99) k=0 for ax, clist in zip(axes, cmap_list): cmap = mpl.colors.ListedColormap(clist) cmap.set_over(clist[0]) cmap.set_under(clist[-1]) ax.imshow(gradient, aspect='auto', cmap=cmap) pos = list(ax.get_position().bounds) x_text = pos[0] - 0.01 y_text = pos[1] + pos[3]/2. fig.text(x_text, y_text, 'cmap_list_%d'%(k+1), va='center', ha='right', fontsize=10) k=k+1 # Turn off *all* ticks & spines, not just the ones with colormaps. for ax in axes: ax.set_axis_off() plt.show() ''' (b)根据RGB字典生成 字典的规律为R,G,B 或/和alpha四个元素,每个元素由3列n行。其中,R,G,B的第一列标记为x,第二列标记为y1,第三列标记为y2.用i来标记行。 在x[i]~x[i+1]之间,红(或绿,或蓝)对应的取值为y2[i]~y1[i+1].以下例, 0~0.25 :红色取值为0~0,绿色取值为0~0,蓝色取值为0.4~1; 0.25~0.5:红色取值为0~0.8,绿色取值为0~0.9,蓝色取值为1~1; 0.5~0.75:红色取值为1~1,绿色取值为0.9~0,蓝色取值为0.9~0; 0.75~1:红色取值为1~0.4,绿色取值为0~0,蓝色取值为0~0; 对于alpha,规则类似于R G B,如上例 0~0.5,透明度取值为1(不透明)~0.3 0.5~1,透明度取值为0.3~1(不透明) ''' import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl cdict = {'red': ((0.0, 0.0, 0.0), (0.25, 0.0, 0.0), (0.5, 0.8, 1.0), (0.75, 1.0, 1.0), (1.0, 0.4, 1.0)), 'green': ((0.0, 0.0, 0.0), (0.25, 0.0, 0.0), (0.5, 0.9, 0.9), (0.75, 0.0, 0.0), (1.0, 0.0, 0.0)), 'blue': ((0.0, 0.0, 0.4), (0.25, 1.0, 1.0), (0.5, 1.0, 0.8), (0.75, 0.0, 0.0), (1.0, 0.0, 0.0)) } cdict1 = cdict.copy() ''' Make a modified version of cdict with some transparency in the middle of the range.cdict1['alpha'] = ((0.0, 1.0, 1.0), (0.25,1.0, 1.0), (0.5, 0.3, 0.3), (0.75,1.0, 1.0), (1.0, 1.0, 1.0)) ''' cmap = mpl.colors.LinearSegmentedColormap('my_cmap',cdict1) N = 1000 array_dg = np.random.uniform(0, 10, size=(N, 2)) colors = np.random.uniform(-2, 2, size=(N,)) plt.scatter(array_dg[:, 0], array_dg[:, 1], c=colors, cmap=cmap) plt.colorbar() plt.show() ''' 利用线性方法制作非线性分布色标 下列例子中,自定义函数make_colormap(seq)就可以实现这个功能,参数seq具体含义为 0.1以下为红色(这个可以随便改动,比如purple也可以) 0.1~0.3由红色线性过渡到白色 0.3~0.9由白色线性过渡到蓝色 0.9以上是蓝色 ''' import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl def make_colormap(seq): """Return a LinearSegmentedColormap seq: a sequence of floats and RGB-tuples. The floats should be increasing and in the interval (0,1). """ seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3] cdict = {'red': [], 'green': [], 'blue': []} for i, item in enumerate(seq): if isinstance(item, float): r1, g1, b1 = seq[i - 1] r2, g2, b2 = seq[i + 1] cdict['red'].append([item, r1, r2]) cdict['green'].append([item, g1, g2]) cdict['blue'].append([item, b1, b2]) return mpl.colors.LinearSegmentedColormap('CustomMap', cdict) c = mpl.colors.ColorConverter().to_rgb rvb = make_colormap( [c('red'),0.1,c('red'), c('white'), 0.33,c('white'), c('green'), 0.9, c('green')]) print(rvb) N = 1000 array_dg = np.random.uniform(0, 10, size=(N, 2)) colors = np.random.uniform(-2, 2, size=(N,)) plt.scatter(array_dg[:, 0], array_dg[:, 1], c=colors, cmap=rvb) plt.colorbar() plt.show()

自定义色标

python 将matplotlib绘制的图表赋给一个img对象 matplotlib输出图形到网页_取值_07

python 将matplotlib绘制的图表赋给一个img对象 matplotlib输出图形到网页_中文显示

python 将matplotlib绘制的图表赋给一个img对象 matplotlib输出图形到网页_html_02

''' cnames = { 'aliceblue': '#F0F8FF', 'antiquewhite': '#FAEBD7', 'aqua': '#00FFFF', 'aquamarine': '#7FFFD4', 'azure': '#F0FFFF', 'beige': '#F5F5DC', 'bisque': '#FFE4C4', 'black': '#000000', 'blanchedalmond': '#FFEBCD', 'blue': '#0000FF', 'blueviolet': '#8A2BE2', 'brown': '#A52A2A', 'burlywood': '#DEB887', 'cadetblue': '#5F9EA0', 'chartreuse': '#7FFF00', 'chocolate': '#D2691E', 'coral': '#FF7F50', 'cornflowerblue': '#6495ED', 'cornsilk': '#FFF8DC', 'crimson': '#DC143C', 'cyan': '#00FFFF', 'darkblue': '#00008B', 'darkcyan': '#008B8B', 'darkgoldenrod': '#B8860B', 'darkgray': '#A9A9A9', 'darkgreen': '#006400', 'darkkhaki': '#BDB76B', 'darkmagenta': '#8B008B', 'darkolivegreen': '#556B2F', 'darkorange': '#FF8C00', 'darkorchid': '#9932CC', 'darkred': '#8B0000', 'darksalmon': '#E9967A', 'darkseagreen': '#8FBC8F', 'darkslateblue': '#483D8B', 'darkslategray': '#2F4F4F', 'darkturquoise': '#00CED1', 'darkviolet': '#9400D3', 'deeppink': '#FF1493', 'deepskyblue': '#00BFFF', 'dimgray': '#696969', 'dodgerblue': '#1E90FF', 'firebrick': '#B22222', 'floralwhite': '#FFFAF0', 'forestgreen': '#228B22', 'fuchsia': '#FF00FF', 'gainsboro': '#DCDCDC', 'ghostwhite': '#F8F8FF', 'gold': '#FFD700', 'goldenrod': '#DAA520', 'gray': '#808080', 'green': '#008000', 'greenyellow': '#ADFF2F', 'honeydew': '#F0FFF0', 'hotpink': '#FF69B4', 'indianred': '#CD5C5C', 'indigo': '#4B0082', 'ivory': '#FFFFF0', 'khaki': '#F0E68C', 'lavender': '#E6E6FA', 'lavenderblush': '#FFF0F5', 'lawngreen': '#7CFC00', 'lemonchiffon': '#FFFACD', 'lightblue': '#ADD8E6', 'lightcoral': '#F08080', 'lightcyan': '#E0FFFF', 'lightgoldenrodyellow': '#FAFAD2', 'lightgreen': '#90EE90', 'lightgray': '#D3D3D3', 'lightpink': '#FFB6C1', 'lightsalmon': '#FFA07A', 'lightseagreen': '#20B2AA', 'lightskyblue': '#87CEFA', 'lightslategray': '#778899', 'lightsteelblue': '#B0C4DE', 'lightyellow': '#FFFFE0', 'lime': '#00FF00', 'limegreen': '#32CD32', 'linen': '#FAF0E6', 'magenta': '#FF00FF', 'maroon': '#800000', 'mediumaquamarine': '#66CDAA', 'mediumblue': '#0000CD', 'mediumorchid': '#BA55D3', 'mediumpurple': '#9370DB', 'mediumseagreen': '#3CB371', 'mediumslateblue': '#7B68EE', 'mediumspringgreen': '#00FA9A', 'mediumturquoise': '#48D1CC', 'mediumvioletred': '#C71585', 'midnightblue': '#191970', 'mintcream': '#F5FFFA', 'mistyrose': '#FFE4E1', 'moccasin': '#FFE4B5', 'navajowhite': '#FFDEAD', 'navy': '#000080', 'oldlace': '#FDF5E6', 'olive': '#808000', 'olivedrab': '#6B8E23', 'orange': '#FFA500', 'orangered': '#FF4500', 'orchid': '#DA70D6', 'palegoldenrod': '#EEE8AA', 'palegreen': '#98FB98', 'paleturquoise': '#AFEEEE', 'palevioletred': '#DB7093', 'papayawhip': '#FFEFD5', 'peachpuff': '#FFDAB9', 'peru': '#CD853F', 'pink': '#FFC0CB', 'plum': '#DDA0DD', 'powderblue': '#B0E0E6', 'purple': '#800080', 'red': '#FF0000', 'rosybrown': '#BC8F8F', 'royalblue': '#4169E1', 'saddlebrown': '#8B4513', 'salmon': '#FA8072', 'sandybrown': '#FAA460', 'seagreen': '#2E8B57', 'seashell': '#FFF5EE', 'sienna': '#A0522D', 'silver': '#C0C0C0', 'skyblue': '#87CEEB', 'slateblue': '#6A5ACD', 'slategray': '#708090', 'snow': '#FFFAFA', 'springgreen': '#00FF7F', 'steelblue': '#4682B4', 'tan': '#D2B48C', 'teal': '#008080', 'thistle': '#D8BFD8', 'tomato': '#FF6347', 'turquoise': '#40E0D0', 'violet': '#EE82EE', 'wheat': '#F5DEB3', 'white': '#FFFFFF', 'whitesmoke': '#F5F5F5', 'yellow': '#FFFF00', 'yellowgreen': '#9ACD32'} '''

颜色的十六进制表示

python 将matplotlib绘制的图表赋给一个img对象 matplotlib输出图形到网页_中文显示

python 将matplotlib绘制的图表赋给一个img对象 matplotlib输出图形到网页_html_02

import numpy as np import matplotlib.pyplot as plt # Have colormaps separated into categories: # http://matplotlib.org/examples/color/colormaps_reference.html cmaps = [('Perceptually Uniform Sequential', [ 'viridis', 'plasma', 'inferno', 'magma']), ('Sequential', [ 'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds', 'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu', 'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']), ('Sequential (2)', [ 'binary', 'gist_yarg', 'gist_gray', 'gray', 'bone', 'pink', 'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia', 'hot', 'afmhot', 'gist_heat', 'copper']), ('Diverging', [ 'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu', 'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic']), ('Qualitative', [ 'Pastel1', 'Pastel2', 'Paired', 'Accent', 'Dark2', 'Set1', 'Set2', 'Set3', 'tab10', 'tab20', 'tab20b', 'tab20c']), ('Miscellaneous', [ 'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern', 'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg', 'hsv', 'gist_rainbow', 'rainbow', 'jet', 'nipy_spectral', 'gist_ncar'])] nrows = max(len(cmap_list) for cmap_category, cmap_list in cmaps) gradient = np.linspace(0, 1, 256) gradient = np.vstack((gradient, gradient)) def plot_color_gradients(cmap_category, cmap_list, nrows): fig, axes = plt.subplots(nrows=nrows) fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99) axes[0].set_title(cmap_category + ' colormaps', fontsize=14) for ax, name in zip(axes, cmap_list): ax.imshow(gradient, aspect='auto', cmap=plt.get_cmap(name)) pos = list(ax.get_position().bounds) x_text = pos[0] - 0.01 y_text = pos[1] + pos[3]/2. fig.text(x_text, y_text, name, va='center', ha='right', fontsize=10) # Turn off *all* ticks & spines, not just the ones with colormaps. for ax in axes: ax.set_axis_off() for cmap_category, cmap_list in cmaps: plot_color_gradients(cmap_category, cmap_list, nrows) plt.show()

显示plt.colormap的所有色标

刻度、标题、标签和图例

legend ():生成默认图例, matplotlib 中的 legend 图例就是为了帮我们展示出 每个数据对应的图像名称. 更好的让读者认识到你的数据结构.。

xlabel、ylabel:设置X轴Y轴标签。

title:设置标题。

xlim、ylim:控制图标的范围。

xticks、yticks: 控制图标的刻度。

gca获取当前坐标轴信息。使用spines设置边框,使用set_color设置边框颜色: 默认白色。

解决中文显示问题:

mpl.rcParams['font.sans-serif'] = ['SimHei']

mpl.rcParams['axes.unicode_minus'] = False

import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import pandas as pd # 设置中文显示 mpl.rcParams['font.sans-serif'] = ['SimHei'] mpl.rcParams['axes.unicode_minus'] = False data = np.arange(-3,3,0.1) x = np.sin(data) y = np.cos(data) # 创建图形 fig = plt.figure() # 画图 plt.plot(x,y,'r--',label = 'x-line') # 生成图例 plt.legend(loc='upper left') #如果没有loc参数则是自动适应 # plt.legend(loc='lower right') #如果没有loc参数则是自动适应 #设置标题 plt.title('进球数') # 设置x/y轴标签 plt.xlabel('x轴') plt.ylabel('y轴') # 设置刻度的范围 # plt.xlim(1,10) # plt.ylim(1,10) # 设置图标的刻度 plt.xticks(np.arange(1,6,1),['中国','2月','3月','4月','5月']) # plt.xticks(np.arange(1,6,1),[str(i)+'月' for i in range(1,6,1)]) plt.yticks(np.arange(1,10)) #写入文本 plt.text(2,6,'这是一个练习图') #相对于坐标轴 fig.text(0.5,0.5,'this is test') #相对于画布 # 说明: # plt.text()依次传入坐标和字符串内容 # x,y 代表传入柱的位置和高度 # '%.2f' 代表传入字符串的内容 # ha='center' 设置文字水平对齐方式,其他参数查看帮助文档 # va='bottom' 设置文字垂直对齐方式,其他参数查看帮助文档 # size 设置字体大小 # 获取坐标轴信息 ax = plt.gca() ax.spines['right'].set_color(None) ax.spines['top'].set_color(None) # ax.spines['left'].set_color(None) # ax.spines['bottom'].set_color(None) # plt.axis('off') # 展示图片 plt.show()

python 将matplotlib绘制的图表赋给一个img对象 matplotlib输出图形到网页_中文显示

python 将matplotlib绘制的图表赋给一个img对象 matplotlib输出图形到网页_html_02

#其中’loc’参数有多种,’best’表示自动分配最佳位置,其余的如下: 'best' : 0, 'upper right' : 1, 'upper left' : 2, 'lower left' : 3, 'lower right' : 4, 'right' : 5, 'center left' : 6, 'center right' : 7, 'lower center' : 8, 'upper center' : 9, 'center' : 10,

loc参数的可选值

设置坐标轴

# Annotation 标注 # 画出基本图 #当图线中某些特殊地方需要标注时,我们可以使用 annotation. matplotlib 中的 annotation 有两种方法, #一种是用 plt 里面的 annotate,一种是直接用 plt 里面的 text 来写标注. '''首先,我们在坐标轴中绘制一条直线.''' import matplotlib.pyplot as plt import numpy as np x = np.linspace(-3, 3, 50) y = 2*x + 1 plt.figure(num=1, figsize=(8, 5),) plt.plot(x, y,) '''移动坐标''' #使用plt.gca获取当前坐标轴信息. 使用.spines设置边框:右侧边框;使用.set_color设置边框颜色:默认白色; 使用.spines设置边框:上边框;使用.set_color设置边框颜色:默认白色; ax = plt.gca() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') #然后我们挪动坐标轴的位置.使用.xaxis.set_ticks_position设置x坐标刻度数字或名称的位置:bottom.(所有位置:top,bottom,both,default,none) ax.xaxis.set_ticks_position('bottom') #使用.spines设置边框:x轴;使用.set_position设置边框位置:y=0的位置;(位置所有属性:outward,axes,data) ax.spines['bottom'].set_position(('data', 0)) #使用.yaxis.set_ticks_position设置y坐标刻度数字或名称的位置:left.(所有位置:left,right,both,default,none) ax.yaxis.set_ticks_position('left') #使用.spines设置边框:y轴;使用.set_position设置边框位置:x=0的位置;(位置所有属性:outward,axes,data) ax.spines['left'].set_position(('data', 0)) '''标注出点(x0, y0)的位置信息.''' x0 = 1 y0 = 2*x0 + 1 plt.plot([x0, x0,], [0, y0,], 'k--', linewidth=2.5) plt.scatter([x0, ], [y0, ], s=50, color='b') '''添加注释 annotate''' # 其中参数xycoords='data' 是说基于数据的值来选位置, xytext=(+30, -30) 和 textcoords='offset points' 对于标注位置的描述 和 xy 偏差值, arrowprops是对图中箭头类型的一些设置. plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle='->', connectionstyle="arc3,rad=.2")) '''添加注释 text ''' plt.text(-3.7, 3, r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',fontdict={'size': 16, 'color': 'r'}) plt.show()

python 将matplotlib绘制的图表赋给一个img对象 matplotlib输出图形到网页_中文显示

python 将matplotlib绘制的图表赋给一个img对象 matplotlib输出图形到网页_html_02

from mpl_toolkits.axisartist.axislines import SubplotZero import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np # 设置中文显示 mpl.rcParams['font.sans-serif'] = ['SimHei'] mpl.rcParams['axes.unicode_minus'] = False fig = plt.figure() ax = SubplotZero(fig, 111) fig.add_subplot(ax) for direction in ["xzero", "yzero"]: # adds arrows at the ends of each axis ax.axis[direction].set_axisline_style("-|>") # adds X and Y-axis from the origin ax.axis[direction].set_visible(True) for direction in ["left", "right", "bottom", "top"]: # hides borders ax.axis[direction].set_visible(False) x = [i for i in range(-10,11)] y = [8 for i in range(len(x))] ax.plot(x, y,'-b',label='y=8') plt.xlim(-10,10) plt.ylim(-10,10) # ax.axis['yzero'].set_label('x轴') # ax.axis['xzero'].set_label('y轴') plt.xticks(x) plt.yticks(x) plt.legend(loc='lower right') plt.show()

View Code

import math import matplotlib as mpl import matplotlib.pyplot as plt import mpl_toolkits.axisartist as axisartist # 设置中文显示 mpl.rcParams['font.sans-serif'] = ['SimHei'] mpl.rcParams['axes.unicode_minus'] = False # 创建画布 fig = plt.figure(figsize=(16, 8)) # 使用axisartist.Subplot方法创建一个绘图区对象ax ax = axisartist.Subplot(fig, 111) # 将绘图区对象添加到画布中 fig.add_axes(ax) # 通过set_visible方法设置绘图区所有坐标轴隐藏 ax.axis[:].set_visible(False) # ax.new_floating_axis代表添加新的坐标轴 ax.axis["x"] = ax.new_floating_axis(0, 0) # 第一个0表示水平线,第二个0表示经过0点。 # 给x坐标轴加上箭头 ax.axis["x"].set_axisline_style("->", size=1.0) # ->表示虚心箭头,size表示箭头的大小。 # 添加y坐标轴,且加上箭头 ax.axis["y"] = ax.new_floating_axis(1, 0) # 1表示竖线,第二个0表示经过0点。 ax.axis["y"].set_axisline_style("-|>", size=1.0) # -|>表示虚心箭头,size表示箭头的大小。 # 设置x、y轴上刻度显示方向 ax.axis["x"].set_axis_direction("top") ax.axis["y"].set_axis_direction("right") x = [i / 10 for i in range(-100, 101)] y = [math.sin(i) for i in x] plt.plot(x, y, '-b', label='y=sin(x)') y1 = [2 ** i for i in x] plt.plot(x, y1, '-k', label='y=2^x') x2 = [i / 10 for i in range(1, 101)] y2 = [math.log(i, 2) for i in x2] plt.plot(x2, y2, '-r', label='y=log2x') plt.plot(x, x, '-g', label='y=x') # 生成图例 plt.legend(loc='lower right') # 设置x轴和y轴的取值范围 plt.xlim(-10, 10) plt.ylim(-10, 10) # 设置x轴和y轴标签名 plt.xlabel('x轴') plt.ylabel('y轴') # 设置显示网格 plt.grid(True) plt.show()

tick 能见度

#当图片中的内容较多,相互遮盖时,我们可以通过设置相关内容的透明度来使图片更易于观察,也即是通过本节中的bbox参数设置来调节图像信息. import matplotlib.pyplot as plt import numpy as np x = np.linspace(-3, 3, 50) y = 0.1*x plt.figure() # 在 plt 2.0.2 或更高的版本中, 设置 zorder 给 plot 在 z 轴方向排序 plt.plot(x, y, linewidth=10, zorder=1) plt.ylim(-2, 2) ax = plt.gca() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.spines['bottom'].set_position(('data', 0)) ax.yaxis.set_ticks_position('left') ax.spines['left'].set_position(('data', 0)) '''然后对被遮挡的图像调节相关透明度,本例中设置 x轴 和 y轴 的刻度数字进行透明度设置''' #中label.set_fontsize(12)重新调节字体大小,bbox设置目的内容的透明度相关参,facecolor调节 box 前景色,edgecolor 设置边框, 本处设置边框为无,alpha设置透明度. for label in ax.get_xticklabels() + ax.get_yticklabels(): label.set_fontsize(12) # 在 plt 2.0.2 或更高的版本中, 设置 zorder 给 plot 在 z 轴方向排序 label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.7, zorder=2)) # label.set_bbox(dict(facecolor='red', edgecolor='None', alpha=0.7, zorder=2)) print(ax.get_xticklabels()+ ax.get_yticklabels()) plt.show()Subplot 子图

subplot:子图,figure对象下创建一个或多个subplot对象(即axes) 用于绘制图像。 subplot(numRows, numCols, plotNum)。

x1 = [1,3,5] y1 = [2,4,5] x2 = [1,4,5] y2 = [3,2,5] # 创建图形 plt.figure() plt.subplot(221) plt.plot(x1,y1,'r--') plt.subplot(223) plt.plot(x2,y2,'b-') plt.show()

Sublots():返回一个图像和多个子图。

参数:

nrows=x, ncols=x, sharex=True, sharey=False, gridspec_kw={'height_ratios':[2,2,1,1]}

例:

fig, ax = plt.subplots(2,2),其中参数分别代表子图的行数和列数,一共有 2x2 个图像。函数返回 一个figure图像和一个子图ax的array列表。

# 生成一个figure 以及子图的列表 fig, ax = plt.subplots(2,2) # 2行 2列 2维列表 for i in range(2): for j in range(2): ax[i][j].plot(np.random.randn(50).cumsum(),'r--') # ax[i,j].plot(np.random.randn(50).cumsum(),'r--') fig, ax = plt.subplots(2,2) # 2行 2列 2维列表 colors=['Reds','Blues'] for i in range(2): for j in range(2): ax1=ax[i][j].scatter(np.random.randn(50).cumsum(),np.random.randn(50),c=np.random.randn(50),cmap=colors[i]) fig.colorbar(ax1,ax=ax[i][j]) #参数mappable理解起来就是我们需要提供一个可以映射颜色的对象,这个对象就是我们作的图,参数ax用来指示colorbar()获取到的渐变色条在哪里显示,ax参数设置成多个Axes对象。 plt.show() '''图像保存''' plt.savefig('zitu.jpg')

子图面向对象的形式:

fig = plt.figure()  #Figure实例,可以添加Axes实例。 ax = fig.add_subplot(111)   #返回Axes实例 参数1,子图的总行数 参数2,子图的总列数 参数3,子图位置 在Figure上添加子图的常用方法。# 创建图形 fig= plt.figure() fig.suptitle('运行效果') #设置总标题 ax1 = fig.add_subplot(321,facecolor='b') #添加子图背景颜色 ax1.plot(np.random.randn(50).cumsum(),'r--') plt.title('this is test') ax2 = fig.add_subplot(322,facecolor='r') ax2.plot(np.random.randn(50).cumsum(),'b-') plt.title('这是一个测试') ax3 = fig.add_subplot(312) ax3.plot(np.random.randn(50).cumsum(),'y--') ax4 = fig.add_subplot(325) ax4.plot(np.random.randn(50).cumsum(),'g-') ax4.set_title('this is test') ax5 = fig.add_subplot(326) ax5.plot(np.random.randn(50).cumsum(),'g-') ax5.set_title('这是一个测试') plt.show()

利用subplot_adjust()函数可以对画的多个子图进行调整,优化间隔,它一共有left、right, bottom, top, wspace, hspase 六个参数,取 值从0至1。

# 创建图形 fig= plt.figure(figsize=(10,10)) #设置总标题 # fig.suptitle('运行效果') plt.suptitle('运行结果') ax1 = fig.add_subplot(221,facecolor='b') #添加子图背景颜色 ax1.plot(np.random.randn(50).cumsum(),'r--') plt.title('this is test') ax2 = fig.add_subplot(222,facecolor='r') ax2.plot(np.random.randn(50).cumsum(),'b-') plt.title('这是一个测试') ax3 = fig.add_subplot(223) ax3.plot(np.random.randn(50).cumsum(),'y--') ax5 = fig.add_subplot(224) ax5.plot(np.random.randn(50).cumsum(),'g-') fig.subplots_adjust(wspace=0,hspace=0) plt.show() #画了多个子图时,在保存的时候出现了以下问题,就是子图之间有重叠。这种情况发生在我调用函数画图后,函数返回一个fig对象(fig=plt.gcf()),利用下面这行: # plt.savefig(savefig_path, bbox_inches='tight', dpi=300) #bbox_inches='tight'帮助删除图片空白部分

共用x轴

import numpy as np import matplotlib.pyplot as plt t = np.arange(0.01, 10.0, 0.01) data1 = np.exp(t) data2 = np.sin(2 * np.pi * t) fig, ax1 = plt.subplots() color = 'tab:red' ax1.set_xlabel('time (s)') ax1.set_ylabel('exp', color=color) ax1.plot(t, data1, color=color) ax1.tick_params(axis='y', labelcolor=color) ax2 = ax1.twinx() color = 'tab:blue' ax2.set_ylabel('sin', color=color) ax2.plot(t, data2, color=color) ax2.tick_params(axis='y', labelcolor=color) plt.xticks(rotation=50) #如果不是共用轴,就可以设置。现在共用X轴就无法使用xticks的rotation来对x周标签旋转 fig.tight_layout() plt.show()常用图形柱状图

matplotlib.pyplot. bar (*args, **kwargs) bar(left, height, width, bottom, * args, align='center', **kwargs)。

参数:

left:数据标量。

height:高。

width:款。

bottom:底端对应Y轴。

align:对齐如果为 "居中", 则将x参数解 释为条形中心的坐标。如果 "边缘", 将条形按其左边缘对齐要对齐右边缘的条形图, 可传递负的宽度和对 align='edge'

import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import pandas as pd # 设置中文显示 mpl.rcParams['font.sans-serif'] = ['SimHei'] mpl.rcParams['axes.unicode_minus'] = False # 设置jupyter中 的显示方式 # %matplotlib tk %matplotlib inline # 设置数据 height = np.array([100,200,300,400]) # y # 设置数据标量 left = np.arange(1,5,1) # 4 x # 设置柱子宽度 n = 4 width = 0.8/4 # 创建figure plt.figure() # 画图 plt.bar(left,height,width = width,color = 'lightskyblue',align = 'center',label = '上海') plt.bar(left-width,height+20,width = width,color = 'red',align = 'center',label = '北京') plt.bar(left+width,height+10,width = width,color = 'yellowgreen',align = 'center',label = '深圳') # 生成图例 plt.legend(loc='upper left') #设置标题 plt.title('旅游人数') #要改 # 设置x/y轴标签 # 要改 plt.xlabel('月份') plt.ylabel('人次/百万') # 设置图标的刻度 plt.xticks(np.arange(1,5,1),['1月','2月','3月','4月']) # 要改 # plt.xticks(np.arange(1,6,1),[str(i)+'月' for i in range(1,6,1)]) plt.yticks(np.arange(100,600,100)) # 获取坐标轴信息 ax = plt.gca() ax.spines['right'].set_color(None) ax.spines['top'].set_color(None) # 展示图片 plt.show()# 设置画板大小 plt.figure(figsize=(10, 6)) # 画出柱状图 plt.barh(left, height, 0.5, color=['r', 'g', 'b','y']) plt.show()直方图

matplotlib.pyplot.hist( x,bins=10,range=None,normed=False,weights=None,cumulative=False,bottom=None, histtype='bar', align='mid',orientation=u'vertical', rwidth=None, log=False,color=None, label=None,stacked=False,hold=None,**kwargs) 。

-- x: 一个列表或者多个列表(表示不同数据集,长度可以不一致)。

– range: 元组 – weights: x里每个元素对bin高度的贡献(默认为1)。

– bottom: 数字或者长度为bins的列表。

– histtype: ['bar' | 'barstacked' | 'step' | 'stepfilled']。

– align: ['left' | 'mid' | 'right']。

– orientation: ['horizontal' | 'vertical']。

– rwidth: bar相对bin的宽度。

– color: 一种颜色或者颜色列表(针对不同数据集)。

import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import pandas as pd # 设置中文显示 mpl.rcParams['font.sans-serif'] = ['SimHei'] mpl.rcParams['axes.unicode_minus'] = False # 设置jupyter中 的显示方式 # %matplotlib tk %matplotlib inline # 设置数据 mu , sigma = 100,15 # x = np.random.randn(10000)*mu*sigma x = np.random.randn(10000).cumsum() plt.figure() plt.hist(x,1000,alpha = 0.5,color = 'red') plt.title('频率图') plt.grid(True) plt.show()散点图

matplotlib.pyplot. scatter (x, y, s=none, c=none, marker=none, cmap= None, norm=none, vmin=none, vmax=none, alpha=none, Linewidths=none, verts=none, edgecolors=none, hold=none, data= None, **kwargs)。

参数:

x,y:相同长度的数组序列。

s :散点的大小标量或形同数组,可选参数,默认20。

c :散点的色彩或颜色序列,可选。

maker:标记风格,可选,默认是‘o’。

norm:数据的亮度。

alpha:散点的透明度

import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import pandas as pd # 设置中文显示 mpl.rcParams['font.sans-serif'] = ['SimHei'] mpl.rcParams['axes.unicode_minus'] = False # 设置jupyter中 的显示方式 # %matplotlib tk %matplotlib inline # 设置数据 x = np.random.randn(1000) y = np.random.randn(1000) plt.scatter(x,y,c = np.random.rand(1000,4),s = np.random.rand(1000)*50,alpha = 0.7) plt.title('aaa') plt.show()饼图

matplotlib.pyplot. pie(x, explode=None, labels=None, colors=('b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'), autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None, radius=None, counterclock=True, wedgeprops=None, textprops=None, center = (0, 0), frame = False )

参数:

x (每一块)的比例,如果sum(x) > 1会使用sum(x)归一化。

labels (每一块)饼图外侧显示的说明文字。

explode (每一块)离开中心距离。

startangle 起始绘制角度,默认图是从x轴正方向逆时针画起,如设定=90则从y轴正方向画起。

shadow 是否阴影。

labeldistance label绘制位置,相对于半径的比例, 如



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有